#!/usr/bin/env python3

'''
162.寻找峰值
https://leetcode.cn/problems/find-peak-element/

'''

class Solution:
    #def findPeakElement(self, nums) -> int: python3版本低的时候使用
    def findPeakElement(self, nums: list[int]) -> int:
        n = len(nums)

        #辅助函数，输入下标i，返回nums[i]的值
        #方便处理 nums[-1]以及nums[n]的边界情况
        def get(i:int) -> int:
            if i == -1 or i == n:
                return float('-inf')  #python infinity  'inf' or '-inf'
            return nums[i]
        
        left, right, ans = 0, n-1, -1
        while left <= right:
            mid = (left + right) // 2
            if get(mid-1) < get(mid) > get(mid+1):   #相当于 与
                ans = mid
                break
            if get(mid) <= get(mid + 1):
                left = mid + 1
            else:
                right = mid - 1

        return ans



if __name__ == '__main__':
    solv = Solution()
    
    nums = [1,2,3,1]
    result = solv.findPeakElement(nums)
    print(result, nums[result])
    
    nums = [1,2,1,3,5,6,4]
    result = solv.findPeakElement(nums)
    print(result, nums[result])

    nums = [1,2,3,3,3,3,3,5,5,5,5,5,5,5,6,4]
    result = solv.findPeakElement(nums)
    print(result, nums[result])
